import axios from 'axios'
import {  ElMessage } from 'element-plus'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 3600000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  (config) => {
    // do something before request is sent
    // return
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data
    if (response.data instanceof Blob) {
      return response
    }
    if (res.code != '200') {
      ElMessage({
        message: res.msg || 'Error',
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(error)
    } 
    return res
  },
  error => {
    console.log(error) // for debug
    ElMessage({
      message: error || 'error',
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
    // return error
  }
)

export default service
